package leetcode_2501_2600;

import java.util.Arrays;

public class LeeCode_2517_2 {
    public static void main(String[] args) {
        System.out.println(maximumTastiness(new int[]{13, 5, 1, 8, 21, 2}, 3));
        System.out.println(maximumTastiness(new int[]{1,3,1}, 2));
    }
    private static int maximumTastiness(int[] price, int k) {
        int n = price.length;
        Arrays.sort(price);
        if (k == 2) return price[n - 1] - price[0];
        int l = 0, r = (price[n - 1] - price[0]) / (k - 1) + 1;
        while (l + 1 < r) {
            int c = l + (r - l) / 2;
            if (check(price, c, k)) {
                l = c;
            } else {
                r = c;
            }
        }
        return l;
    }

    private static boolean check(int[] price, int c, int k) {
        int n = price.length;
        int count = 1;
        int pre = price[0];
        for (int i = 1; i < n; i++) {
            if (price[i] >= pre + c) {
                ++count;
                pre = price[i];
            }
            if(count == k) return true;
        }
        return false;
    }
}
